use super::*;
use indicatif::{ProgressBar, ProgressStyle};
use std::time::Duration;

const IMAGEMAGICK_BIN: &str = "convert";

pub static CMD_CHECK_IMAGEMAGICK: PrequireCmd = PrequireCmd::new(
  IMAGEMAGICK_BIN,
  "--version",
  Some(Link::new(
    "安装 ImageMagick",
    "https://imagemagick.org/index.php",
  )),
  Some(formatcp!(
    "Not found {0}!!\nPlease install {0} first.",
    IMAGEMAGICK_BIN
  )),
);

#[derive(Debug, Subcommand)]
pub enum ImageMagickComands {
  Convert {
    output: String,

    #[arg(required = true, trailing_var_arg = true)]
    glob_pattern: Vec<String>,
  },
}

pub fn serve_image_magick(command: &ImageMagickComands) {
  match command {
    ImageMagickComands::Convert {
      glob_pattern,
      output,
    } => {
      println!("convert glob pattern files to tiff...");
      // println!("glob_pattern=>{:?}", glob_pattern);
      ConvertCmd::new(glob_pattern, output.to_string()).exec();
    }
  }
}

pub struct ConvertCmd<'a> {
  glob_pattern: &'a [String],
  output_tiff: String,
}

impl<'a> ConvertCmd<'a> {
  pub fn new(glob_pattern: &'a [String], output: String) -> Self {
    let output_tiff = iif!(
      output.ends_with(".tiff"),
      output,
      format!("{}.tiff", output)
    );

    ConvertCmd {
      glob_pattern,
      output_tiff,
    }
  }
}

impl<'a> BinaryCommand for ConvertCmd<'a> {
  type Output = ();
  fn exec(&self) -> Self::Output {
    if cfg!(target_os = "windows") {
      panic!("no impl for windows!")
    } else {
      let pb = ProgressBar::new_spinner();
      pb.enable_steady_tick(Duration::from_millis(120));
      pb.set_style(
        ProgressStyle::with_template("{spinner:.blue} {msg}")
          .unwrap()
          // For more spinners check out the cli-spinners project:
          // https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
          .tick_strings(&[
            "▹▹▹▹▹",
            "▸▹▹▹▹",
            "▹▸▹▹▹",
            "▹▹▸▹▹",
            "▹▹▹▸▹",
            "▹▹▹▹▸",
            "▪▪▪▪▪",
          ]),
      );
      pb.set_message("转换中`...");
      let output = Command::new(IMAGEMAGICK_BIN)
        .args(self.glob_pattern)
        .arg(&self.output_tiff)
        .output();
      self.process_stdout::<&str>(output, None, None);

      // thread::sleep(Duration::from_secs(5));
      pb.finish_with_message("完成");
    }
  }
}
